<?php

namespace app\api\controller;

use app\api\model\RushOrder;
use app\api\model\RushOrderEntrust;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use app\common\model\User;
use EasyWeChat\Foundation\Application;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 抢购-卖家仓库
 */
class RushSeller extends Api
{
    protected $noNeedLogin = ['confirmGetMoneyAction','complainReason'];
    protected $noNeedRight = '*';

    /**
     * @ApiTitle    (列表)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=type, type=integer, required=false, description="订单类型:all=全部,haveup=已上架,waitget=待确认收款,complain=投诉订单,complete=已完成")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652680764",
        "data": {
            "total": 2, //数据总数
            "per_page": 15,
            "current_page": 1,
            "last_page": 1,
            "data": [{ //列表
                "id": 1, //ID
                "order_no": "R2022050953531024", //订单号
                "order_status": "1", //订单状态:0=待付款,1=待确认收款,2=待上架,3=已上架,4=已完成
                "complain_status": "0", //投诉状态:0=未投诉,1=已投诉
                "rushtime": "2022-05-21 20:10:20", //抢购时间
                "goods_name": "商品一", //商品名称
                "goods_price": "7000.00", //商品价格
                "goods_no": "123", //商品编码
                "goods_image": "http://rbv6is607.hn-bkt.clouddn.com/uploads/20220508/13cb1b8e54988cbb3710cc79897f0096.jpg", //商品图片
                "time_name": "狂欢上午场", //所属场次
                "buyer": { //交易方
                    "id": 1008, //ID
                    "nickname": "攻击力", //昵称
                    "avatar": "", //头像
                    "url": "/u/1008"
                },
                "order_status_text": "待确认收款", //订单状态文字
                "complain_status_text": "未投诉"
            }]
        }
    })
     */
    public function list()
    {
        $type = $this->request->param('type');
        $where = [
            'seller_id' => $this->auth->id,
        ];
        switch ($type){
            case 'all':
                break;
            case 'haveup':
                $where['order_status'] = ['in',['0','3']];
                break;
            case 'waitget':
                $where['order_status'] = '1';
                break;
            case 'complain':
                $where['complain_status'] = '1';
                break;
            case 'complete':
                $where['order_status'] = ['in',['4','5']];
                break;
            default:
                $this->error('参数不合法');
        }
        $table_name = RushOrder::getTable();
        $list = RushOrder::with(['buyer'])
            ->where($where)
            ->order($table_name.'.rushtime desc')
            ->paginate()
            ->each(function($v){
                //卖家不显示待付款订单
                if($v['order_status'] == '0'){
                    $v['order_status'] = '3';
                }
                $v->visible(['id','order_no','order_status','complain_status','rushtime','goods_name','goods_no','goods_image','goods_price','time_name','buyer']);
                //抢购时间
                $v->rushtime = !empty($v['rushtime']) ? date('Y-m-d H:i:s',$v['rushtime']) : '';
                //交易方
                $v->getRelation('buyer')->visible(['id','avatar','nickname']);
            });
        $this->success('',$list);
    }

    /**
     * @ApiTitle    (查看付款凭证)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652237913",
        "data": {
            "id": 1,
            "order_status": "0",
            "payment_voucher": [ //凭证组图
                "http://petsdemo.qiniu.brofirst.cn123",
                "http://petsdemo.qiniu.brofirst.cn456"
            ],
            "order_status_text": "Order_status 0",
            "complain_status_text": ""
        }
    })
     */
    public function paymentVoucherView()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('seller_id',$this->auth->id)->where('id',$order_id)->field('id,order_status,payment_voucher')->find();
        empty($order) && $this->error('订单不存在');
        !in_array($order['order_status'],['0','1']) && $this->error('订单不合法');
        $this->success('',$order);
    }

    /**
     * @ApiTitle    (确认收款)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单状态:-1=全部,0=待付款,1=待确认收款,2=待上架,4=已提货")
     * @ApiReturn   ({
        "code":"状态码",
        "msg": "提示消息"
    })
     */
    public function confirmGetMoney()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('seller_id',$this->auth->id)->where('id',$order_id)->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '1' && $this->error('订单不合法');
        $res = self::confirmGetMoneyAction($order);
        $res['code'] == 0 && $this->error($res['msg']);
        $this->success('成功');
    }

    /**
     * 确认收款操作
     * @ApiInternal
     */
    public static function confirmGetMoneyAction($order)
    {
        \think\Log::write('确认收款操作：'.json_encode($order));
        Db::startTrans();
        try {
            //订单状态变为：待上架
            $order->save(['order_status'=>'2','confirmtime'=>time()]);
            //计算收益和收益率
            $old_order = RushOrder::where('new_order_id',$order['id'])->field('id')->find();
            if($old_order){
                $entrust = RushOrderEntrust::where('order_id',$old_order['id'])->where('pay_status','1')->find();
                if($entrust){
                    //收益=委托上架金额-抢购价格-支付手续费金额
                    $profit = $entrust['entrust_price']-$entrust['goods_price']-$entrust['pay_price'];
                    //收益率(%)=(收益/抢购价格)*100
                    $profit_rate = round(($profit/$entrust['goods_price'])*100,1);
                    $entrust->save([
                        'profit' => $profit,
                        'profit_rate' => $profit_rate,
                        'profit_time' => time()
                    ]);
                }
            }

            //删除重复的队列记录，（订单逻辑不同于其他项目，所以需要删除）
            $payload = json_encode([
                'job' => "\\app\\api\\job\\RushOrderAutoOper@autoSendScore",
                'data' => ['order_id'=>$order['id']],
            ]);
            Db::name('jobs')->where('payload',$payload)->delete();
            // 确认收款后两小时再给分销积分
            $minue = 120;
            \think\Queue::later(($minue * 60), '\app\api\job\RushOrderAutoOper@autoSendScore', ['order_id' => $order['id']], 'rushbuy');

            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }catch (Exception $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }
        return ['code' => 1,'msg' => '取消成功'];
    }

    /**
     * @ApiTitle    (投诉订单-订单展示)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652254547",
        "data": {
            "id": 3, //订单ID
            "order_no": "R2022051154100974", //订单号
            "order_status": "0", //订单状态:0=待付款,1=待确认收款,2=待委托上架（待提货）,3=买家已委托上架,4=已提货,11=已取消
            "goods_name": "商品一", //商品名称
            "goods_price": "7000.00", //商品价格
            "goods_image": "http://petsdemo.qiniu.brofirst.cn/uploads/20220508/13cb1b8e54988cbb3710cc79897f0096.jpg", //封面图
            "time_name": "狂欢上午场", //所属场次
            "buyer": { //交易方
                "id": 1000, //ID
                "nickname": "Xue", //昵称
                "avatar": "", //头像
                "url": "/u/1000"
            },
            "order_status_text": "Order_status 0", //订单状态文字
            "complain_status_text": "Complain_status 0"
        }
    })
     */
    public function complainView()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('seller_id',$this->auth->id)->where('id',$order_id)->find();
        empty($order) && $this->error('订单不存在');
        $order->visible(['id','order_no','order_status','goods_name','goods_image','goods_price','time_name','buyer']);
        $order['buyer']->visible(['id','avatar','nickname']);
        $this->success('',$order);
    }

    /**
     * @ApiTitle    (投诉订单)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiParams   (name=complain_reason, type=string, required=true, description="投诉原因")
     * @ApiParams   (name=complain_content, type=string, required=true, description="投诉描述")
     * @ApiParams   (name=complain_voucher, type=string, required=true, description="投诉凭证，多图片用英文逗号隔开")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息"
    })
     */
    public function complain()
    {
        $post = $this->request->param();
        empty($post['order_id']) && $this->error('请选择投诉订单');
        empty($post['complain_reason']) && $this->error('请选择投诉原因');
        $order = RushOrder::where('seller_id',$this->auth->id)->where('id',$post['order_id'])->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '1' && $this->error('订单不合法');
        $post['complain_status'] = '1';
        $order->allowField('complain_status,complain_reason,complain_content,complain_voucher')->save($post);
        $this->success('');
    }

    /**
     * @ApiTitle    (投诉订单-原因列表)
     * @ApiMethod   (POST)
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652690358",
        "data": [ //原因列表
            "款项未到账",
            "到账金额少于应收金额",
            "其他"
        ]
    })
     */
    public function complainReason()
    {
        $data = array_values(config('site.rush_complain_reason'));
        $this->success('',$data);
    }
}
